package com.qf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.mapper.DtsStorageMapper;
import com.qf.pojo.DtsStorage;
import com.qf.service.DtsStorageService;
import com.qf.util.AliyunOSSUtil;
import com.qf.util.UUID;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author Zwnan
 */
@Service
public class DtsStorageServiceImpl implements DtsStorageService {

    @Autowired
    private DtsStorageMapper dtsStorageMapper;

    /**
     * aliyun.oss.endpoint=http://oss-cn-beijing.aliyuncs.com
     *
     * aliyun.oss.accessKeyId=LTAI5tKjZYJaoHoa2Hh2CKub
     *
     * aliyun.oss.accessKeySecret=veDVqYtpRKse4zN58NlhjI9Ws0i4n0
     *
     * aliyun.oss.bucketName=gp14-zwn-file
     * @param bytes
     * @param originalFilename
     * @param size
     * @return
     */

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Override
    public DtsStorage create(byte[] file, String originalFilename, long size) throws Exception {

        String ext = FilenameUtils.getExtension(originalFilename);
        String fileName = UUID.randomUUID().toString().replaceAll("-", "")+"."+ext;

        String path = AliyunOSSUtil.uploadImage(endpoint,accessKeyId,accessKeySecret,bucketName,fileName,file);
        DtsStorage dtsStorage = new DtsStorage();
        dtsStorage.setName(fileName);
        dtsStorage.setKey(fileName);
        dtsStorage.setType(ext);
        dtsStorage.setUrl(path);
        dtsStorage.setSize(size);
        dtsStorage.setAddTime(new Date());
        dtsStorage.setUpdateTime(new Date());
        dtsStorage.setDeleted(false);
        dtsStorageMapper.insert(dtsStorage);
        return dtsStorage;
    }

    @Override
    public IPage<DtsStorage> selectPage(Integer page, Integer limit, String sort, String order) {
        IPage<DtsStorage> iPage = new Page<>(page,limit);
        QueryWrapper<DtsStorage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", false);

        return dtsStorageMapper.selectPage(iPage,queryWrapper);
    }

    @Override
    public void delete(DtsStorage dtsStorage) {
        dtsStorage.setDeleted(true);
        dtsStorageMapper.updateById(dtsStorage);
    }

    @Override
    public void update(DtsStorage dtsStorage) {
        dtsStorageMapper.updateById(dtsStorage);
    }
}
